﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@using ST.Torch.WebApi.Core.Manage
@using ST.Torch.WebApi.Web.Core;
@inherits UtilRazorPage<object>
@{
    Layout = "~/Views/Shared/__ComponentLayout.cshtml";
    //Layout = "~/Views/Shared/__ComponentLayout.cshtml";

    string randomId = Guid.NewGuid().ToString();
    var ImgUrl = ConfigData.ImgUrl;
}


<div style="padding: 16px;"></div>

<form style="padding: 16px;padding-right:30px" class="layui-form" action="" lay-filter="edit-data_@randomId">
    <input type="text" name="Id" placeholder="" autocomplete="off" class="layui-input" style="display:none">
    <div class="layui-form-item">
        <label class="layui-form-label">@L("输入框")</label>
        <div class="layui-input-block">
            <input type="text" name="Title" required lay-verify="required" placeholder="" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">@L("选择框")</label>
        <div class="layui-input-block">
            <select name="City" lay-verify="required">
                <option value=""></option>
                <option value="0">北京</option>
                <option value="1">上海</option>
                <option value="2">广州</option>
                <option value="3">深圳</option>
                <option value="4">杭州</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">@L("复选框")</label>
        <div class="layui-input-block">
            <input type="checkbox" name="Likes[写作]" title="写作" value="写作">
            <input type="checkbox" name="Likes[阅读]" title="阅读" value="阅读">
            <input type="checkbox" name="Likes[发呆]" title="发呆" value="发呆">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">@L("单选框")</label>
        <div class="layui-input-block">
            <input type="radio" name="Sex" value="0" title="男">
            <input type="radio" name="Sex" value="1" title="女">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">@L("开关")</label>
        <div class="layui-input-block">
            <input type="checkbox" name="Switch" lay-skin="switch" value="true">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">@L("文本域")</label>
        <div class="layui-input-block">
            <textarea name="Desc" placeholder='@L("请输入内容")' class="layui-textarea"></textarea>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">@L("图片")</label>
        <div class="layui-input-block">

            <input type="text" style="display:none" id="ImgInputEle_@randomId" name="ImgUrl" placeholder="" autocomplete="off" class="layui-input">
            <div class="layui-upload">
                <button type="button" class="layui-btn" id="ImgButtonEle_@randomId">@L("上传图片")</button>
                <div class="layui-upload-list">
                    <img class="layui-upload-img" id="ImgEle_@randomId" style="height:50px;width:50px">
                    <p id="ImgText_@randomId"></p>
                </div>
                <div style="width: 95px;" id="ImgProgressEle_@randomId">
                    <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="ImgProgress_@randomId">
                        <div class="layui-progress-bar" lay-percent=""></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">@L("富文本框")</label>
        <div class="layui-input-block">
            <textarea id="TinymceEle_@randomId" name="DescTinymce" placeholder='@L("请输入内容")' class="layui-textarea"></textarea>
            
        </div>
    </div>

    <div class="layui-form-item FormSubmit" style="text-align:center;left:50px" >
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo">@L("立即提交")</button>

        </div>
    </div>
</form>
@section footer
 {
  <script> 
        //Demo
        layui.use(['form', 'toast', 'upload', 'element','tinymce'], function () {
            var form = layui.form;
            var toast = layui.toast;
            var upload = layui.upload;
            var element = layui.element;
            var tinymce = layui.tinymce;
            //var editId = '@GetValue("Id", "null")';
            var buttonEle = null;
            form.on('submit(formDemo)', function (data) {
                buttonEle = button.load({ elem: this });
                 Update(data);
                return false;
            });

            function Query() {
                $.ajax({
                    url: '/api/FormData/First',//发送请求
                    type: 'POST',
                    success: function (result) {
                      if (result.Succeeded) {
                          var Likes=[];
                          if(result.Data.Like !=null){
                              Likes= result.Data.Like.split(',');
                          }
                         for(var i in Likes){
                              $("input[name='Likes["+Likes[i]+"]']").prop("checked", true);
                         }
                          
                          form.val("edit-data_@randomId", result.Data);
                           $('#ImgEle_@randomId').attr('src', FileHttpApiUrl+result.Data.ImgUrl); //图片链接（base64）
                           $('#ImgProgressEle_@randomId').hide();
                           initTinymce('TinymceEle_@randomId',"");
                         
                      } else {
                          toast.error({
                              message: '@L("查询失败")',
                          });
                      }
                    }
                });
            }
            Query();
            function Update(data) {
                //复选框处理
                var filed="Like";
                var fileds="Likes";
                var TempStr="";//拼接
                for(var i in data.field){
                    if((i).indexOf(fileds)>-1){
                         TempStr+=data.field[i]+","
                    }
                }
                TempStr=TempStr.substring(0,TempStr.length-1);
                data.field[filed]=TempStr
                //富文本框处理
                var filed="DescTinymce";
                var content = TinymceEle.getContent()
                data.field[filed]=content;
                $.ajax({
                    type: 'POST',
                     url: '/api/FormData/Update',//发送请求
                    data: data.field,
                    success: function (result) {
                        buttonEle.stop();
                        if (result.Succeeded) {
                           
                            toast.success({
                                message: '@L("修改成功")',
                            });
                        } else {
                            var msgError = '@L("修改失败")';
                            if (result.Errors != "") {
                                msgError = result.Errors
                            }
                            toast.error({
                                message: msgError,
                            });
                        }
                    }, error: function (err) {
                        buttonEle.stop();

                        toast.error({
                            message: err.status + ":" + err.statusText,
                        });
                    }
                });
            }
            //=========上传图片Start
             //常规使用 - 普通图片上传
        var uploadInst = upload.render({
            elem: '#ImgButtonEle_@randomId'
               // , url: '/Api/System/Uploadfiles/UserImg' //上传接口
               , url: 'api/File/UploadFile' //上传接口
              ,data:{
                      DirectoryName:'Temp'
              }
            , accept: 'images' //只允许上传图片
            , acceptMime: 'image/*' //只筛选图片
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#ImgEle_@randomId').attr('src', result); //图片链接（base64）
                });
                $('#ImgProgressEle_@randomId').show();
                element.progress('ImgProgress_@randomId', '0%'); //进度条复位
                layer.msg('@L("上传中")', { icon: 16, time: 0 });
            }
            , done: function (res) {
                //如果上传失败
                // if (res.code > 0) {
                //     return layer.msg('上传失败');
                // }
                if (res.code == 200) {
                    $("#ImgInputEle_@randomId").val(res.data)
                } else {
                    layer.msg(res.msg);

                }
                //上传成功的一些操作
                //……
                $('#ImgText_@randomId').html(''); //置空上传失败的状态
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#ImgText_@randomId');
                demoText.html('<span style="color: #FF5722;">@L("上传失败")</span> <a class="layui-btn layui-btn-xs demo-reload">@L("重试")</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
            //进度条
            , progress: function (n, elem, e) {
                element.progress('ImgProgress_@randomId', n + '%'); //可配合 layui 进度条元素使用
                if (n == 100) {
                    layer.msg('@L("上传完毕")', { icon: 1 });
                }
            }
        });
        //=============================End

        //===================富文本框
        var OssUrl="/api/File/UploadFile"
        var TinymceEle=null
          function initTinymce(id, contectStr) {
                TinymceEle = tinymce.render({
                    elem: "#" + id
                    , height: 500
                    , width: '100%'
                    , content: contectStr // 设置初始值
                    , images_upload_handler: function (blobInfo, succFun, failFun) {
                        var xhr, formData;
                        var file = blobInfo.blob();//转化为易于理解的file对象
                        xhr = new XMLHttpRequest();
                        xhr.withCredentials = false;
                        xhr.open('POST', OssUrl);
                        xhr.onload = function () {
                            var json;
                            if (xhr.status != 200) {
                                failFun('HTTP Error: ' + xhr.status);
                                return;
                            }
                            json = JSON.parse(xhr.responseText);
                            if (json.code != 200) {
                                failFun('Invalid JSON: ' + xhr.responseText);
                                return;
                            }
                            //succFun('@ImgUrl'+ json.result);
                            succFun('@ImgUrl'+ json.data);
                        };
                        formData = new FormData();
                        formData.append('file', file, file.name);//此处与源文档不一样
                        formData.append('DirectoryName','TinymceImg' );//此处与源文档不一样
                        xhr.send(formData);
                    }
                    , init_instance_callback: function (editor) {
                        autoImportImage(editor, 'TinymceImg');
                    }
                });
            }
        //===================富文本框End

        });
   </script> 
}